package com.zjlanyun.eplus.utils;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.nohttp.HttpListener;
import com.zjlanyun.eplus.nohttp.HttpRequest;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateManager {

	private Context mContext;
	private Toastor toastor;
	private ProgressBar mProgress;
	private TextView progress_tv;
	private boolean interceptFlag = false;
	private Dialog downloadDialog;
	private Thread downLoadThread;
	private String apkUrl = "";
	private String savePath = "";
	private String saveFileName = "";
	private int progress;
	private PackageManager mPackageManager;
	private PackageInfo mPackageInfo = null;
	private int newVersionCode = 1; // 新代码版本号
	private String newVersionName;
	private SharedPreferences userinfo;
	private int cancelVersionCode = 1; // 取消更新的版本号
	private boolean manualCheck = false; // true表示手动检查更新，会提示用户当前版本是否是最新版本

	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				progress_tv.setText(progress + "%");
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		this.savePath = context.getExternalCacheDir() + "/update/";
		this.saveFileName = savePath + "UpdateRelease.apk";
		userinfo = context.getSharedPreferences("userinfo", 0);
		cancelVersionCode = userinfo.getInt("cancelVersionCode", 1); // 取消更新的版本号
		toastor = new Toastor();
		mPackageManager = context.getPackageManager();
		try {
			mPackageInfo = mPackageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 自动检查更新
	 */
	public void checkUpdateInfo() {
		if (NetworkUtils.getNetworkType(mContext).equals("WIFI")) {
			showNoticeDialog();
		}
	}
	
	/**
	 * 手动检查更新
	 */
	public void manualCheckUpdate(){
		manualCheck = true;
		cancelVersionCode = 1;
		showNoticeDialog();
	}

	/**
	 * 显示更新提示
	 */
	private void showNoticeDialog() {
		HttpRequest client = new HttpRequest(mContext, SPData.getConfig().getString("update_url",""));
		client.getRequest().add("customer_number", "16980");//E+通用客户端
//		client.getRequest().add("customer_number", "17454");//E-cloud通用客户端
		client.send(new HttpListener<JSONObject>() {
			@Override
			public void onSucceed(int what, Response<JSONObject> response) {
				JSONObject data = response.get().optJSONObject("data");
				newVersionName = data.optString("last_version_android"); // 新代码版本号
				// 判断新代码版本号与取消更新的代码版本号是否相同，不相同则进入更新
				// 新代码版本号大于当前代码版本号则进入更新
				if (compareVersion(newVersionName, mPackageInfo.versionName) == 1) {
					apkUrl = data.optString("app_download_url_android");
					new AlertView("提示", "有新版本更新", "暂不更新", new String[]{"立即更新"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
						@Override
						public void onItemClick(Object o, int position) {
							if (position == -1) {
								cancelUpdate(newVersionCode);
							} else if (position == 0){
								showDownloadDialog();
							}
						}
					}).show();
				}else{
					Toastor.getInstance().showShortToast("当前已是最新版本");
				}
			}

			@Override
			public void onFailed(int what, Response<JSONObject> response) {

			}

			@Override
			public void onFinish(int what) {

			}
		});
	}

	/**
	 * 显示更新下载进度条
	 */
	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("更新中");

		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.download_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		progress_tv = (TextView) v.findViewById(R.id.progress_tv);

		builder.setView(v);
		builder.setNegativeButton("取 消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();

		downloadApk();
	}

	/**
	 * 取消更新
	 */
	private void cancelUpdate(int versionCode) {
		SPData.getUserinfo().putInt("cancelVersionCode", versionCode);
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装更新包
	 */
	private void installApk() {
		downloadDialog.dismiss();
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(i);
	}

	/**
	 * 版本名称比较
	 * @param version1 新版本名称
	 * @param version2 当前客户端版本名称
     * @return 1有最新版本，0版本相同，-1当前版本大于新版本
     */
	private int compareVersion(String version1, String version2) {
		if (version1.equals(version2)) {
			return 0;
		}

		String[] version1Array = version1.split("\\.");
		String[] version2Array = version2.split("\\.");

		int index = 0;
		int minLen = Math.min(version1Array.length, version2Array.length);
		int diff = 0;

		while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
			index ++;
		}

		if (diff == 0) {
			for (int i = index; i < version1Array.length; i ++) {
				if (Integer.parseInt(version1Array[i]) > 0) {
					return 1;
				}
			}

			for (int i = index; i < version2Array.length; i ++) {
				if (Integer.parseInt(version2Array[i]) > 0) {
					return -1;
				}
			}

			return 0;
		} else {
			return diff > 0 ? 1 : -1;
		}
	}
}
